package com.mazaiting.generator.config;

import com.mazaiting.generator.config.query.*;
import com.mazaiting.generator.domain.entity.DatasourceEntity;
import com.mazaiting.generator.enums.DbTypeEnum;
import com.mazaiting.generator.utils.DbUtil;
import lombok.Data;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * 代码生成器 数据源
 *
 * @author 阿沐 babamu@126.com
 */
@Data
public class GenDataSource {
    /**
     * 数据源ID
     */
    private Long id;
    /**
     * 数据库类型
     */
    private DbTypeEnum dbTypeEnum;
    /**
     * 数据库URL
     */
    private String connUrl;
    /**
     * 用户名
     */
    private String username;
    /**
     * 密码
     */
    private String password;

    /**
     * 抽象查询
     */
    private AbstractQuery dbQuery;

    /**
     * 数据库连接
     */
    private Connection connection;

    public GenDataSource(DatasourceEntity entity) throws SQLException, ClassNotFoundException {
        this.id = entity.getId();
        this.dbTypeEnum = DbTypeEnum.valueOf(entity.getDbType());
        this.connUrl = entity.getConnUrl();
        this.username = entity.getUsername();
        this.password = entity.getPassword();

        if (dbTypeEnum == DbTypeEnum.MySQL) {
            this.dbQuery = new MySqlQuery();
        } else if (dbTypeEnum == DbTypeEnum.Oracle) {
            this.dbQuery = new OracleQuery();
        } else if (dbTypeEnum == DbTypeEnum.PostgreSQL) {
            this.dbQuery = new PostgreSqlQuery();
        } else if (dbTypeEnum == DbTypeEnum.SQLServer) {
            this.dbQuery = new SQLServerQuery();
        }

        this.connection = DbUtil.getConnection(this);
    }

    public GenDataSource(Connection connection) throws SQLException {
        this.id = 0L;
        this.dbTypeEnum = DbTypeEnum.valueOf(connection.getMetaData().getDatabaseProductName());

        if (dbTypeEnum == DbTypeEnum.MySQL) {
            this.dbQuery = new MySqlQuery();
        } else if (dbTypeEnum == DbTypeEnum.Oracle) {
            this.dbQuery = new OracleQuery();
        } else if (dbTypeEnum == DbTypeEnum.PostgreSQL) {
            this.dbQuery = new PostgreSqlQuery();
        } else if (dbTypeEnum == DbTypeEnum.SQLServer) {
            this.dbQuery = new SQLServerQuery();
        }

        this.connection = connection;
    }
}
